package cn.itcast.bos.service.take_delivery.imp;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.AreaDao;
import cn.itcast.bos.dao.base.Fixed_AreaDao;
import cn.itcast.bos.dao.take_delivery.OrderDao;
import cn.itcast.bos.dao.take_delivery.workBillDao;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.service.take_delivery.OrderService;

@Service
@Transactional
public class OrderServiceImp implements OrderService {

	@Autowired
	private OrderDao orederDao;
	@Autowired
	private AreaDao areaDao;

	@Autowired
	private Fixed_AreaDao fixedAreaDao;

	@Autowired
	private workBillDao workBillDAO;

	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;

	@Override
	public void order_Save(Order order) {
		
		System.out.println(order+"_______________");
		String uuid = UUID.randomUUID().toString();
		order.setOrderNum(uuid);

		// 通过省市区,查询分区关键字,配置地址,基于分区实现自动分单
		Area sendArea = order.getSendArea();

		Area persistArea = areaDao.findByProvinceAndCityAndDistrict(sendArea.getProvince(), sendArea.getCity(),
				sendArea.getDistrict());
		Area recArea = order.getSendArea();
		Area persistrecArea = areaDao.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());
		order.setSendArea(persistArea);
		order.setRecArea(persistrecArea);

		String fixedAreaId = WebClient
				.create("http://localhost:9002")
				.path("crm_management")
				.path("services")
				.path("customerService")
				.path("findFixedAreaIdByAddress")
				.query("address", order.getSendAddress())
				.type(MediaType.APPLICATION_JSON)
				.accept(MediaType.APPLICATION_JSON)
				.get(String.class);
		if (fixedAreaId != null) {
			// 根据客户定区ID查询出定区
			FixedArea fixedArea = fixedAreaDao.findOne(fixedAreaId);
			// 查询出定区下边的快递员
			Courier courier = fixedArea.getCouriers().iterator().next();
			// 判断定区下边是否关联的有快递员
			if (courier != null) {
				System.out.println(courier.getName());
				saveOrder(order, courier);
				generateWorkBill(order);
				return;
			}
		}
		// 通过省市区,查询分区关键字,配置地址,基于分区实现自动分单

		for (SubArea subArea : persistArea.getSubareas()) {
			// 当前下单客户地址是否包含分区 关键字
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				// 从当前定区找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						saveOrder(order, courier);
						// 生成工单,发送短信
						generateWorkBill(order);
						return;
					}
				}

			}
		}

		for (SubArea subArea : persistArea.getSubareas()) {
			// 当前下单客户地址是否包含分区 辅助关键字
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				// 从当前定区找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				if (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						saveOrder(order, courier);
						// 生成工单,发送短信
						generateWorkBill(order);
						return;
					}
				}

			}
		}
		// 进入人工分单
		order.setOrderType("2");
		orederDao.save(order);

	}

	private void saveOrder(Order order, Courier courier) {
		// 自动分单成功
		System.out.println("自动分单成功");
		// 将快递员关联上订单
		order.setCourier(courier);
		order.setOrderType("1");
		// 保存订单
		orederDao.save(order);
	}

	private void generateWorkBill(final Order order) {
		// 生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新"); // 设置工单类型
		workBill.setPickstate("新单"); // 设置工单取件状态
		workBill.setBuildtime(new Date());// 设置工单生成时间
		workBill.setRemark(order.getRemark());// 设置订单备注
		final String randomNumeric = RandomStringUtils.randomNumeric(4);
		workBill.setSmsNumber(randomNumeric);// 设置短信序号
		workBill.setOrder(order);// 设置工单的订单信息
		workBill.setCourier(order.getCourier());// 设置工单的快递员
		workBillDAO.save(workBill);

		jmsTemplate.send("bos_sms", new MessageCreator() {
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());
				mapMessage.setString("msg", "短信序号：" + randomNumeric + ",取件地址：" + order.getSendAddress() + ",联系人:"
						+ order.getSendName() + ",手机:" + order.getSendMobile() + "，快递员捎话：" + order.getSendMobileMsg());
				return mapMessage;
			}
		});

		// 修改工单状态
		workBill.setPickstate("已通知");
	}

	@Override
	public Order findByorderNum(String orderNum) {
		return orederDao.findByorderNum(orderNum);
	}

}
